package com.sjme.interceptor;

import com.sjme.domain.user.User;
import com.sjme.threadLocal.UserThreadLocalUtil;
import feign.Feign;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@ConditionalOnClass(Feign.class) // 使用引入feign的模块才生效
public class GlobalFeignInterceptor implements RequestInterceptor {
    @Value("${spring.application.name}")
    private String applicationName; // 各模块的application.yml中的模块名称

    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 为远程调用添加全局请求头
        requestTemplate.header("X-Request-Source",applicationName);
        // 从ThreadLocalUtil中获取本次请求的线程中的用户信息，传递用户id
        User user = UserThreadLocalUtil.getUser();
        if (user != null) {
            requestTemplate.header("userId",user.getId());
        }
        log.info("为Feign请求添加全局头：{}",requestTemplate.headers());
    }
}
